package com.carboncntr.struts.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.actions.DispatchAction;

import com.carboncntr.helper.CustomerHelper;
import com.carboncntr.helper.HistoryHelper;
import com.carboncntr.struts.form.RegistrationForm;
import com.carboncntr.tables.Customer;

public class RegistrationAction extends DispatchAction {

	public ActionForward init(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
		HttpSession session = (HttpSession)request.getSession();
		Customer c = (Customer)session.getAttribute("Customer");
		RegistrationForm regForm = (RegistrationForm)form;
		if(c != null) {
			double carbonBal = HistoryHelper.getCarbonBalance(c.getCustomerId());
			regForm.setCarbonBalance(carbonBal);
			regForm.setFirst(c.getFirst());
			regForm.setLast(c.getLast());
			regForm.setConfirmPassword(c.getPassword());
			regForm.setPassword(c.getPassword());
			regForm.setEmail(c.getEmail());
			regForm.setUserName(c.getUserName());
			regForm.setZip(c.getZip());
		}
		return mapping.findForward("begin");
	}
	
	public ActionForward submit(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
		HttpSession session = (HttpSession)request.getSession();
		Customer c = (Customer)session.getAttribute("Customer");
		RegistrationForm regForm = (RegistrationForm)form;
		
		if(c != null) {
			c = CustomerHelper.updateCustomer(c.getCustomerId(), regForm.getFirst(), regForm.getLast(), regForm.getPassword(),
					regForm.getEmail(), regForm.getZip());
			session.setAttribute("Customer", c);
		}else {
			String userName = regForm.getUserName();
			Customer tempC = CustomerHelper.getCustomerByUserName(userName);
			if(tempC == null) {
				Long custId = CustomerHelper.saveCustomer(regForm.getFirst(), regForm.getLast(), regForm.getUserName(), regForm.getPassword(),
						regForm.getEmail(), regForm.getZip());
				tempC = CustomerHelper.getCustomerById(custId);
				session.setAttribute("Customer", tempC);
			}else {
				ActionMessages messages = new ActionMessages();
				messages.add("", new ActionMessage("username.used"));
				saveMessages(request, messages);
				return mapping.findForward("begin");
			}
		}
		return mapping.findForward("home");
	}
	
	
}
